package com.lovely602.thread.countdownlatch;

import java.util.concurrent.CountDownLatch;

/**
 * @author lizhixing
 */
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        final int totalThreads = 3;
        CountDownLatch latch = new CountDownLatch(totalThreads);

        for (int i = 0; i < totalThreads; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 正在工作");
                try {
                    Thread.sleep(1000); // 模拟工作
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 完成工作");
                latch.countDown(); // 计数减一
            }).start();
        }

        System.out.println("主线程等待所有子线程完成");
        latch.await(); // 等待计数器为零
        System.out.println("所有子线程完成，主线程继续执行");
    }

}
